﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonNet48.Extend
{
    /// <summary>
    /// 字符串类型转换扩展类
    /// </summary>
    public static class StringConvertExtend
    {
        /// <summary>
        /// 字符串转数值
        /// </summary>
        /// <typeparam name="T">数值类型</typeparam>
        /// <param name="sVal">字符串值</param>
        /// <param name="numStyle">字符串样式(NumberStyles枚举类型)</param>
        /// <returns></returns>
        public static T? ConvertToNum<T>(this string sVal, NumberStyles numStyle) where T : struct, IConvertible, IComparable<T>
        {
            try
            {
                if (string.IsNullOrWhiteSpace(sVal)) return default(T);
                Type type = typeof(T);
                var mParse = type.GetMethod("Parse", new Type[] { typeof(string), typeof(NumberStyles) });
                var oRet = mParse?.Invoke(null, new object[] { sVal, numStyle });
                return (T?)oRet;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return default(T?);
            }
        }

    }
}
